package com.qiantu.phone.manager;

import android.content.Context;
import android.graphics.Rect;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;

import androidx.recyclerview.widget.RecyclerView;

import com.qiantu.phone.R;

public class CenterFlowLayoutManager extends RecyclerView.LayoutManager {
    private final String TAG = this.getClass().getName();
    private SparseArray<View> cachedViews = new SparseArray();
    private SparseArray<Rect> layoutPoints = new SparseArray<>();
    private int maxWidth;
    private int totalHeight;
    private int mContentHeight;
    private int mOffset;
    private int marginHorizontal;
    private int marginVertical;
    private int spanCount;

    public CenterFlowLayoutManager(Context context, int spanCount) {
//        this.maxWidth = maxWidth;
        this.spanCount = spanCount;
//        marginHorizontal = context.getResources().getDimensionPixelSize(R.dimen.dp_12);
//        marginVertical = context.getResources().getDimensionPixelSize(R.dimen.dp_12);
        marginHorizontal = 0;
        marginVertical = 0;
    }

    @Override
    public boolean supportsPredictiveItemAnimations() {
        return true;
    }

    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        for (int i = 0; i < getItemCount(); ++i) {
            View v = cachedViews.get(i);
            Rect rect = layoutPoints.get(i);
            layoutDecorated(v, rect.left, rect.top, rect.right, rect.bottom);
        }
        mOffset = 0;
    }

    @Override
    public RecyclerView.LayoutParams generateDefaultLayoutParams() {
        return new RecyclerView.LayoutParams(RecyclerView.LayoutParams.WRAP_CONTENT, RecyclerView.LayoutParams.WRAP_CONTENT);
    }

    @Override
    public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state) {
        return dx;
    }

    @Override
    public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
        int shouldOffset = 0;
        Log.i("luzx", "mOffset:" + mOffset);
        if (mContentHeight - totalHeight > 0) {
            int targetOffset = mOffset + dy;
            if (targetOffset < 0) {
                targetOffset = 0;
            } else if (targetOffset > (mContentHeight - totalHeight)) {
                targetOffset = (mContentHeight - totalHeight);
            }
            shouldOffset = targetOffset - mOffset;
            offsetChildrenVertical(-shouldOffset);
            mOffset = targetOffset;
        }
        return shouldOffset;
    }

    @Override
    public boolean canScrollHorizontally() {
        return true;
    }

    @Override
    public boolean canScrollVertically() {
        return true;
    }

    @Override
    public void onAdapterChanged(RecyclerView.Adapter oldAdapter, RecyclerView.Adapter newAdapter) {
        removeAllViews();
    }

    @Override
    public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
        super.onMeasure(recycler, state, widthSpec, heightSpec);

        final int widthMode = View.MeasureSpec.getMode(widthSpec);
        final int heightMode = View.MeasureSpec.getMode(heightSpec);
        final int widthSize = View.MeasureSpec.getSize(widthSpec);
        final int heightSize = View.MeasureSpec.getSize(heightSpec);

        int height;

        switch (widthMode) {
            case View.MeasureSpec.UNSPECIFIED:
                Log.d(TAG, "WidthMode is unspecified.");
                break;
            case View.MeasureSpec.AT_MOST:
                break;
            case View.MeasureSpec.EXACTLY:
                break;
        }

        removeAndRecycleAllViews(recycler);
        recycler.clear();
        cachedViews.clear();

        mContentHeight = 0;

        int left = getPaddingLeft();
        int top = getPaddingTop();

        int maxTop = top;

        for (int i = 0; i < getItemCount(); ++i) {
            View v = recycler.getViewForPosition(i);
            addView(v);
            measureChildWithMargins(v, 0, 0);
            cachedViews.put(i, v);
        }

        for (int i = 0; i < getItemCount(); ++i) {
            View v = cachedViews.get(i);
//            RecyclerView.LayoutParams rl = (RecyclerView.LayoutParams)v.getLayoutParams();
            int w = getDecoratedMeasuredWidth(v);
            int h = getDecoratedMeasuredHeight(v);
            int count = getItemCount() > 3 ? 3 : getItemCount();
            maxWidth = w * count + getPaddingRight() + getPaddingLeft();
            int remainder = getItemCount() - 1 - (i - 1);
            if(remainder == 1 && getItemCount() % spanCount != 0){
                if (left == getPaddingLeft()) {
                    left = (int) ((maxWidth - w) / 2f);
                    top = maxTop;
                }
                Rect rect = new Rect(left, top, left + w, top + h);
                layoutPoints.put(i, rect);
                left += w;
            }else if(remainder == 2 && getItemCount() % spanCount != 0){
                int rectLeft = (int) ((maxWidth - w * 2) / 2f);
                top = maxTop;
                Rect rect = new Rect(rectLeft, top, rectLeft + w, top + h);
                layoutPoints.put(i, rect);
                left = rectLeft + w;
            }else{
                //第一个不加左边距比较，直接放在最左边
                if(i == 0){
                    Rect rect = new Rect(left, top, left + w, top + h);
                    layoutPoints.put(i, rect);
                    left += w;
                }else{
                    if (w + marginHorizontal > maxWidth - left) {
                        left = getPaddingLeft();
                        top = maxTop;
                        Rect rect = new Rect(left, top, left + w, top + h);
                        layoutPoints.put(i, rect);
                        left += w;
                    }else{
                        left += marginHorizontal;
                        Rect rect = new Rect(left, top, left + w, top + h);
                        layoutPoints.put(i, rect);
                        left += w ;
                    }
                }
            }
            if (top + h >= maxTop) {
                maxTop = top + h + marginVertical;
            }
        }
        mContentHeight = maxTop - getPaddingTop();
        height = mContentHeight + getPaddingTop() + getPaddingBottom();
        switch (heightMode) {
            case View.MeasureSpec.EXACTLY:
                height = heightSize;
                break;
            case View.MeasureSpec.AT_MOST:
                if (height > heightSize) {
                    height = heightSize;
                }
                break;
            case View.MeasureSpec.UNSPECIFIED:
                break;
        }

        totalHeight = height - getPaddingTop() - getPaddingBottom();

        setMeasuredDimension(maxWidth, height);
    }

//    @Override
//    public void onDetachedFromWindow(RecyclerView view, RecyclerView.Recycler recycler) {
//        super.onDetachedFromWindow(view, recycler);
//        mOffset = 0;
//    }

//    @Override
//    public void onAttachedToWindow(RecyclerView view) {
//        mOffset = 0;
//        super.onAttachedToWindow(view);
//    }
}
